<template>
  <div class="orders-container">
    <div class="page-header">
      <h2>订单管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单号或商品"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
          class="search-input"
        />
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          class="date-picker"
        />
      </div>
    </div>

    <!-- 左右分栏布局 -->
    <div class="orders-layout">
      <!-- 左侧订单列表 -->
      <div class="orders-list">
        <div class="list-header">
          <span>订单列表</span>
          <span class="order-count">共 {{ total }} 条</span>
        </div>

        <div class="order-items" v-loading="loading">
          <div
            v-for="order in orders"
            :key="order.id"
            class="order-item"
            :class="{ active: selectedOrder && selectedOrder.id === order.id }"
            @click="selectOrder(order)"
          >
            <div class="order-item-header">
              <span class="order-no">{{ order.orderNo }}</span>
              <div class="order-amount">¥{{ order.total.toFixed(2) }}</div>
            </div>
            <div class="order-item-info">
              <div class="order-meta">
                <span class="order-time">{{ formatDate(order.createdAt) }}</span>
                <span class="order-channel">{{ order.channel ? order.channel.name : '店内' }}</span>
              </div>
              <el-tag :type="getStatusType(order.status)" size="small">
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>
          </div>

          <!-- 空数据状态 -->
          <div v-if="!loading && orders.length === 0" class="empty-data">
            <i class="el-icon-inbox" style="font-size: 40px;"></i>
            <p>暂无订单数据</p>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total"
            small
          />
        </div>
      </div>

      <!-- 右侧订单详情 -->
      <div class="order-detail-panel">
        <div v-if="selectedOrder" class="order-detail">
          <div class="detail-header">
            <h2>订单详情</h2>
            <div class="detail-actions">
              <el-button
                type="primary"
                @click="printOrder(selectedOrder)"
                :disabled="selectedOrder.status === 'cancelled'"
              >
                打印订单
              </el-button>
              <el-button
                type="danger"
                @click="cancelOrder(selectedOrder)"
                :disabled="selectedOrder.status === 'cancelled' || selectedOrder.status === 'refunded'"
              >
                取消订单
              </el-button>
            </div>
          </div>

          <div class="order-info-section">
            <el-row :gutter="24">
              <el-col :span="12">
                <div class="info-card">
                  <h4 class="card-title">基本信息</h4>
                  <div class="info-item">
                    <label>订单号</label>
                    <span class="value">{{ selectedOrder.orderNo }}</span>
                  </div>
                  <div class="info-item">
                    <label>创建时间</label>
                    <span class="value">{{ formatDate(selectedOrder.createdAt) }}</span>
                  </div>
                  <div class="info-item">
                    <label>操作员</label>
                    <span class="value">{{ selectedOrder.user ? selectedOrder.user.name : '未知' }}</span>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-card">
                  <h4 class="card-title">订单状态</h4>
                  <div class="info-item">
                    <label>状态</label>
                    <el-tag :type="getStatusType(selectedOrder.status)" size="large">
                      {{ getStatusText(selectedOrder.status) }}
                    </el-tag>
                  </div>
                  <div class="info-item">
                    <label>渠道</label>
                    <span class="value">{{ selectedOrder.channel ? selectedOrder.channel.name : '店内' }}</span>
                  </div>
                  <div class="info-item">
                    <label>总金额</label>
                    <span class="amount">¥{{ selectedOrder.total.toFixed(2) }}</span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 商品列表 -->
          <div class="products-section">
            <h3 class="section-title">商品明细</h3>
            <el-table :data="selectedOrder.items" border class="products-table">
              <el-table-column prop="product.name" label="商品名称" min-width="200">
                <template #default="scope">
                  <span class="product-name">{{ scope.row.product.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="120" align="center">
                <template #default="scope">
                  <span class="quantity">{{ scope.row.quantity }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="120" align="right">
                <template #default="scope">
                  <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="小计" width="120" align="right">
                <template #default="scope">
                  <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 备注信息 -->
          <div v-if="selectedOrder.note" class="note-section">
            <h3 class="section-title">订单备注</h3>
            <div class="note-content">{{ selectedOrder.note }}</div>
          </div>

          <!-- 支付信息 -->
          <div v-if="selectedOrder.payments && selectedOrder.payments.length > 0" class="payment-section">
            <h3 class="section-title">支付信息</h3>
            <el-table :data="selectedOrder.payments" border class="payment-table">
              <el-table-column prop="method" label="支付方式" width="150">
                <template #default="scope">
                  <span class="payment-method">{{ getPaymentMethod(scope.row.method) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="支付金额" width="120" align="right">
                <template #default="scope">
                  <span class="payment-amount">¥{{ scope.row.amount.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="支付状态" width="120">
                <template #default="scope">
                  <el-tag :type="getPaymentStatusType(scope.row.status)">
                    {{ getPaymentStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="支付时间" min-width="160">
                <template #default="scope">
                  <span class="payment-time">{{ formatDate(scope.row.createdAt) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 未选择订单时的提示 -->
        <div v-else class="no-selection">
          <i class="el-icon-document" style="font-size: 60px; color: #ddd;"></i>
          <p>请选择左侧订单查看详情</p>
        </div>
      </div>
    </div>

    <!-- 小票预览对话框 -->
    <el-dialog
      title="小票预览"
      v-model="receiptDialogVisible"
      width="400px"
      :before-close="handleReceiptDialogClose"
    >
      <OrderReceipt
        v-if="currentReceiptOrder"
        :order="currentReceiptOrder"
        ref="receiptRef"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="receiptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePrint">确认打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import OrderReceipt from '@/components/OrderReceipt.vue'

// 状态数据
const loading = ref(false)
const orders = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const searchQuery = ref('')
const dateRange = ref([])
const selectedOrder = ref(null)

// 小票相关状态
const receiptDialogVisible = ref(false)
const currentReceiptOrder = ref(null)
const receiptRef = ref(null)

// 设置自动刷新
let refreshInterval = null

onMounted(() => {
  // 设置默认日期为今天
  const today = new Date()
  const todayStr = today.toISOString().split('T')[0] // 格式为YYYY-MM-DD
  
  // 使用相同的日期字符串，因为value-format="YYYY-MM-DD"
  dateRange.value = [todayStr, todayStr]
  
  console.log(`默认日期范围: ${dateRange.value[0]} 到 ${dateRange.value[1]}`)
  
  fetchOrders()
  
  // 每30秒自动刷新一次订单数据
  refreshInterval = setInterval(() => {
    fetchOrders()
  }, 30000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams({
      page: currentPage.value,
      limit: pageSize.value
    })
    
    if (searchQuery.value) {
      params.append('search', searchQuery.value)
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      // 由于使用了value-format="YYYY-MM-DD"，dateRange.value已经是字符串格式
      const startDate = dateRange.value[0]
      const endDate = dateRange.value[1]
      
      params.append('startDate', startDate)
      params.append('endDate', endDate)
      
      console.log(`查询日期范围: ${startDate} 到 ${endDate}`)
    }
    
    // 调用API获取订单
    const response = await api.get(`/orders?${params.toString()}`)
    
    if (response.data.status === 'success') {
      orders.value = response.data.data || []
      total.value = response.data.meta?.total || response.data.data?.length || 0
      console.log('获取到订单数据:', orders.value.length, '条')
    } else {
      // 只有在真正的错误情况下才显示错误信息
      if (response.data.message && response.data.message !== 'undefined') {
        ElMessage.error('获取订单失败: ' + response.data.message)
      } else {
        console.log('暂无订单数据')
        orders.value = []
        total.value = 0
      }
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    // 不显示错误消息，而是设置空数据
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 日期格式化
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'paid': '已支付',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'paid': 'success',
    'completed': 'success',
    'cancelled': 'info',
    'refunded': 'danger'
  }
  return typeMap[status] || ''
}

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methodMap = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'mixed': '混合支付'
  }
  return methodMap[method] || method
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  const statusMap = {
    'pending': '处理中',
    'completed': '已完成',
    'failed': '失败',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取支付状态类型
const getPaymentStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'completed': 'success',
    'failed': 'danger',
    'refunded': 'info'
  }
  return typeMap[status] || ''
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 处理日期变化
const handleDateChange = () => {
  currentPage.value = 1
  fetchOrders()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

// 选择订单
const selectOrder = async (order) => {
  try {
    // 获取完整订单信息
    const response = await api.get(`/orders/${order.id}`)

    if (response.data.status === 'success') {
      selectedOrder.value = response.data.data
    } else {
      ElMessage.error('获取订单详情失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 打印订单
const printOrder = async (order) => {
  try {
    // 获取完整订单信息（如果还没有）
    let fullOrder = order
    if (!order.items || order.items.length === 0) {
      const response = await api.get(`/orders/${order.id}`)
      if (response.data.status === 'success') {
        fullOrder = response.data.data
      } else {
        ElMessage.error('获取订单详情失败')
        return
      }
    }

    // 设置当前要打印的订单并显示预览对话框
    currentReceiptOrder.value = fullOrder
    receiptDialogVisible.value = true
  } catch (error) {
    console.error('准备打印订单失败:', error)
    ElMessage.error('准备打印订单失败')
  }
}

// 处理打印
const handlePrint = () => {
  if (receiptRef.value) {
    receiptRef.value.print()
    receiptDialogVisible.value = false
    ElMessage.success('小票已发送到打印机')
  }
}

// 处理小票对话框关闭
const handleReceiptDialogClose = () => {
  receiptDialogVisible.value = false
  currentReceiptOrder.value = null
}

// 取消订单
const cancelOrder = (order) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.orderNo} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API取消订单，使用订单号而不是数字ID
      const response = await api.put(`/orders/by-order-no/${order.orderNo}/status`, {
        status: 'cancelled'
      })
      
      if (response.data.status === 'success') {
        ElMessage.success(`订单 ${order.orderNo} 已取消`)
        // 更新本地订单状态
        order.status = 'cancelled'
        // 如果当前选中的是这个订单，也要更新选中订单的状态
        if (selectedOrder.value && selectedOrder.value.id === order.id) {
          selectedOrder.value.status = 'cancelled'
        }
      } else {
        ElMessage.error('取消订单失败: ' + response.data.message)
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.date-picker {
  width: 350px;
}

/* 左右分栏布局 */
.orders-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

/* 左侧订单列表 */
.orders-list {
  width: 600px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 2px solid #e4e7ed;
  background: #f8f9fa;
  font-weight: 600;
  font-size: 16px;
}

.order-count {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.order-items {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.order-item {
  padding: 18px 24px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
}

.order-item:hover {
  background-color: #f5f7fa;
}

.order-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #409eff;
}

.order-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-no {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.order-item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-time {
  font-size: 13px;
  color: #909399;
}

.order-amount {
  font-weight: 700;
  color: #f56c6c;
  font-size: 16px;
}

.order-channel {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.pagination-container {
  padding: 20px 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
}

/* 右侧订单详情 */
.order-detail-panel {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  display: flex;
  flex-direction: column;
}

.order-detail {
  padding: 30px;
  flex: 1;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e4e7ed;
}

.detail-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.detail-actions {
  display: flex;
  gap: 12px;
}

.order-info-section {
  margin-bottom: 30px;
}

.info-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  border: 1px solid #e4e7ed;
}

.card-title {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
  padding: 8px 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  font-size: 15px;
}

.info-item .value {
  color: #303133;
  font-size: 15px;
  font-weight: 500;
}

.info-item .amount {
  font-weight: 700;
  color: #f56c6c;
  font-size: 20px;
}

.products-section,
.note-section,
.payment-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.note-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin: 0;
  color: #606266;
  font-size: 15px;
  line-height: 1.6;
  border: 1px solid #e4e7ed;
}

/* 表格样式优化 */
.products-table,
.payment-table {
  font-size: 14px;
}

.products-table :deep(.el-table__header-wrapper) th {
  background-color: #f5f7fa;
  font-weight: 600;
  font-size: 15px;
  height: 50px;
}

.products-table :deep(.el-table__body-wrapper) td {
  height: 50px;
}

.product-name {
  font-weight: 500;
  color: #303133;
  font-size: 15px;
}

.quantity {
  font-weight: 600;
  color: #409eff;
  font-size: 15px;
}

.price,
.subtotal {
  font-weight: 600;
  color: #f56c6c;
  font-size: 15px;
}

.payment-table :deep(.el-table__header-wrapper) th {
  background-color: #f5f7fa;
  font-weight: 600;
  font-size: 15px;
  height: 50px;
}

.payment-table :deep(.el-table__body-wrapper) td {
  height: 50px;
}

.payment-method,
.payment-time {
  font-size: 14px;
  color: #303133;
}

.payment-amount {
  font-weight: 600;
  color: #f56c6c;
  font-size: 15px;
}

/* 未选择订单时的提示 */
.no-selection {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.no-selection i {
  font-size: 80px;
  margin-bottom: 20px;
  color: #ddd;
}

.no-selection p {
  margin-top: 15px;
  font-size: 18px;
  color: #909399;
}

/* 空数据状态的样式 */
.empty-data {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-data p {
  font-size: 14px;
  margin: 10px 0 0;
}
</style>